/*
 * SubServerThread.java
 *
 * Created on August 14, 2006, 11:07 AM
 *
 */
package org.letva.copie.subserver.threads;

import java.awt.datatransfer.*;
import java.io.*;
import java.net.*;
import org.letva.copie.common.message.Message;
import org.letva.copie.subserver.*;

/**
 * Nit koja se pokrene kada ima subServer koji zeli da se dirketno poveze na ovaj
 * tako da ova nit obavlja "serverski" deo te komunikacije sa subServerom. Posto
 * jedan subServer drugom moze da salje samo Clipboard, tako da se <B>ne vrti u petlji</B>
 * vec se samo zapocne, posalje Clipboard i to je to.
 * @author Vuk Nikolic
 */
public class SubServerThread extends Thread {

	/** Creates a new instance of SubServerThread */
	public SubServerThread(Socket s, SubServer ss) {
		super("SubServerThread");
		mySocket = s;
		mySubServer = ss;
	}

	@Override
	public void run() {
		System.out.println("SubServerThread: poceo run");
		// cim smo dosli do ovde, znaci neki klijent na drugom racunaru je uradio
		// paste from ovog podservera, sto znaci da njemu treba da prosledim
		// moj Clipboard, odosno Clipboard mojih Clienata, ali posto sam na
		// ISTOJ MASINI to je moj sistemski klipbord.
		Object reply = null;
		try {
			// unutrasnji try je za proveru da li je doslo do neocekivanog
			// tipa (flavora) na klipboardu
			ObjectOutput out = new ObjectOutputStream(mySocket.getOutputStream());
			try {
				/*
				Transferable content = myClipboard.getContents(this);
				// ovde gledaj dal je string ili filelist
				String s = (String)content.getTransferData(DataFlavor.stringFlavor);

				reply = new Message("subServer","subServer",s);
				 */
				reply = myProtocol.getClipboardContent();
			} catch (UnsupportedFlavorException ex) {
				// posto nije dozvoljen flavor salji poruku na odrediste sa tim obavestenjem.
				System.out.println("SubServerThread: UnSupportedFlavor");
				reply = new Message("subServer", "subServer", "UnSupportedFlavor");
				((Message) reply).setType("system");

			}

			out.writeObject(reply);
			out.flush();

			// posto je gotov, da izbrisemo ovaj subServer.
			String subServerUrl = mySocket.getInetAddress().toString();
			mySubServer.removeConnectedSubServer(subServerUrl);

			mySubServer.decActiveSubServerThreads();

			out.close();
			mySocket.close();
		} catch (IOException e) {
			e.printStackTrace();
			mySubServer.getMyWindow().setDialogException("Connection Error", "Problems with input/output operations");
		}
		System.out.println("SubServerThread: gotov run");

	}
	private Socket mySocket = null;
	private SubServer mySubServer = null;
	private SubServerProtocol myProtocol = SubServer.getProtocol();
}
